package com.detrum.sportcamera;

import android.app.Service;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.detrum.base.BaseActivity;
import com.detrum.base.BaseFinal;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.costomview.SaveView;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.finals.WifiFinal;
import com.detrum.sportcamera.fragment.BigImageFragment;
import com.detrum.sportcamera.fragment.CodeRateFragment;
import com.detrum.sportcamera.fragment.CutDownFragment;
import com.detrum.sportcamera.fragment.ExposureFragment;
import com.detrum.sportcamera.fragment.RatiosFragment;
import com.detrum.sportcamera.fragment.WBFragment;
import com.detrum.sportcamera.service.WifiService;
import com.detrum.sportcamera.service.WifiServiceCallback3;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import static com.detrum.base.BaseFinal.dcam;

public class PreviewActivity extends BaseActivity implements TextureView.SurfaceTextureListener, View.OnClickListener, WBFragment.OnFragmentInteractionListener
        , ExposureFragment.OnFragmentInteractionListener, RatiosFragment.OnFragmentInteractionListener, BigImageFragment.OnFragmentInteractionListener,
        CodeRateFragment.OnFragmentInteractionListener,CutDownFragment.OnFragmentInteractionListener {
    private TextureView textureView;
    private SurfaceTexture surfaceTexture;
    private Surface mSurface;
    private MediaCodec videoCodec, audioCodec;
    private WBFragment wbFragment;
    private ExposureFragment exposureFragment;
    private RatiosFragment ratiosFragment;
    private BigImageFragment bigImageFragment;
    private CodeRateFragment codeRateFragment;
    private CutDownFragment cutDownFragment;
    private int wbmode, exposuremode, ratiosmode, rate,cutDownMode;
    private HashMap<Integer,Integer>cutDownMap = new HashMap<>();
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;

    private WifiService wifiService;
    private WifiConn wifiConn;
    private Intent wifiIntent;

    private RelativeLayout right_rl;
    private View media_control;
    private TextView video_time,djs_tv;
    private Switch switch_btn;
    private ImageView wb_iv, exposure_iv, ratios_iv, camera_iv, pic_1, rate_iv,photo_iv,video_iv,battery_iv;
    private SaveView space_iv;
    private int showFlag = Integer.MAX_VALUE;
    private int cameraTag;
    private boolean videoStart;
    private long currentTime;
    private String photoPath;
    private boolean isResume;

    private FrameLayout params_fl_2;
    private boolean isFail;
    private boolean isCreateView;

    private Handler handler = new Handler(Looper.getMainLooper());

    private class TimeRunnable implements Runnable {
        private int duration;

        public TimeRunnable(int duration) {
            this.duration = duration;
        }

        @Override
        public void run() {
            if (videoStart) {
                long time = System.currentTimeMillis() - currentTime;
                Drawable drawableLeft;
                if((time/1000)%2==0){
                    drawableLeft = getResources().getDrawable(R.mipmap
                            .video_time_hide);
                    drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                }else{
                    drawableLeft = getResources().getDrawable(R.mipmap
                            .video_time);
                    drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                }
                if(isResume){
                    video_time.setCompoundDrawables(drawableLeft,null,null,null);
                    video_time.setText(paserTime(time+duration*1000l));
                    handler.postDelayed(this, 1000);
                }
            }
        }
    }

    private String paserTime(long milliseconds) {
        SimpleDateFormat format = new SimpleDateFormat("mm:ss");
        return format.format(new Date(milliseconds));
    }

    private WifiServiceCallback3 wifiServiceCallback3 = new WifiServiceCallback3() {
        @Override
        public void receivePreview(final byte[] bytes, final int length) {
            if (bytes != null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(videoCodec==null){
                            return;
                        }
                        try {
                            decodeVideo(bytes, length);
                        } catch (Exception e) {
                            LogUtils.e("Exception = ");
                        }
                    }
                });
            }
        }

        @Override
        public void previewFail(int type) {
            LogUtils.i("type = "+type+"   isResume = "+isResume);
            if(isFail){
                return;
            }
            if(type == WifiFinal.PreviewSocketTimeout){
                if(isResume){
                    isFail = true;
                    // TODO: 2018/5/23 测试关闭
                    MyMethod.ShowDiaLogFinish(PreviewActivity.this,R.string.connect_timeout);
                }
                if(SportStatic.isLoginPre){
                    if(wifiService!=null){
                        wifiService.LogoutDevice();
                    }
                    SportStatic.isLoginPre = false;
                    ServiceStatic.isWifiDeviceConnect = false;
                }

            }else if(type == WifiFinal.PreviewSocketIOException){
                if(isResume){
                    // TODO: 2018/5/23 测试关闭
                    MyMethod.ShowDiaLogFinish(PreviewActivity.this,R.string.data_exception);
                }
            }
        }

        @Override
        public void getCodeRate(int Rate) {
            rate = Rate;
            LogUtils.e("PreviewActivity getCodeRate = " + Rate);
            if (codeRateFragment == null) {
                codeRateFragment = CodeRateFragment.newInstance();
            }
            codeRateFragment.setmParam1(Rate);
            showFragment(codeRateFragment);
            rate_iv.setImageResource(R.mipmap.qingxidu_2);
            wb_iv.setImageResource(R.mipmap.wb_1);
            exposure_iv.setImageResource(R.mipmap.exposure_1);
            ratios_iv.setImageResource(R.mipmap.ratio_1);
            showFlag = 4;
        }

        @Override
        public void getWB(int wbMode) {
            wbmode = wbMode;
            if (wbFragment == null) {
                wbFragment = WBFragment.newInstance();
            }
            wbFragment.setmParam1(wbMode);
            showFragment(wbFragment);
            wb_iv.setImageResource(R.mipmap.wb_2);
            rate_iv.setImageResource(R.mipmap.qingxidu_1);
            exposure_iv.setImageResource(R.mipmap.exposure_1);
            ratios_iv.setImageResource(R.mipmap.ratio_1);
            Drawable drawableLeft = getResources().getDrawable(R.mipmap
                    .djs_1);
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
            djs_tv.setCompoundDrawables(drawableLeft, null, null, null);
            showFlag = 0;
        }

        @Override
        public void getExposure(int exposureMode) {
            exposuremode = exposureMode;
            LogUtils.i("exposureMode = " + exposureMode);
            if (exposureFragment == null) {
                exposureFragment = ExposureFragment.newInstance();
            }
            exposureFragment.setmParam1(exposureMode);
            showFragment(exposureFragment);
            wb_iv.setImageResource(R.mipmap.wb_1);
            rate_iv.setImageResource(R.mipmap.qingxidu_1);
            exposure_iv.setImageResource(R.mipmap.exposure_2);
            ratios_iv.setImageResource(R.mipmap.ratio_1);
            Drawable drawableLeft = getResources().getDrawable(R.mipmap
                    .djs_1);
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
            djs_tv.setCompoundDrawables(drawableLeft, null, null, null);
            showFlag = 1;
        }

        @Override
        public void getRatios(int ratiosMode) {
            LogUtils.e("PreviewActivity getRatios ratiosMode = " + ratiosMode);
            ratiosmode = ratiosMode;
            if (ratiosFragment == null) {
                ratiosFragment = RatiosFragment.newInstance();
            }
            ratiosFragment.setmParam1(ratiosMode);
            showFragment(ratiosFragment);
            wb_iv.setImageResource(R.mipmap.wb_1);
            rate_iv.setImageResource(R.mipmap.qingxidu_1);
            exposure_iv.setImageResource(R.mipmap.exposure_1);
            ratios_iv.setImageResource(R.mipmap.ratio_2);
            Drawable drawableLeft = getResources().getDrawable(R.mipmap
                    .djs_1);
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
            djs_tv.setCompoundDrawables(drawableLeft, null, null, null);
            showFlag = 2;
        }

        @Override
        public void setCodeRate(int rate) {
            LogUtils.e("PreviewActivity setCodeRate = " + rate);
            if (showFlag == 4) {
                codeRateFragment.setParamsSuccess(rate);
            }
        }

        @Override
        public void setWB(int wbMode) {
            if (showFlag == 0) {
                wbFragment.setParamsSuccess(wbMode);
            }
        }

        @Override
        public void setRatios(int ratiosMode) {
            LogUtils.e("PreviewActivity ratiosMode = " + ratiosMode);
            if (showFlag == 2) {
                ratiosFragment.setParamsSuccess(ratiosMode);
            }
        }

        @Override
        public void setExposure(int exposureMode) {
            if (showFlag == 1) {
                exposureFragment.setProgress(exposureMode);
            }
        }

        @Override
        public void startVideo(boolean type,int duration) {
            LogUtils.i("duration = "+duration);
            if(type){
                videoStart = true;
                TimeRunnable timeRunnable = new TimeRunnable(duration);
                currentTime = System.currentTimeMillis();
                video_time.setVisibility(View.VISIBLE);
                switch_btn.setChecked(true);
                cameraTag = 1;
                switch_btn.setEnabled(false);
                photo_iv.setImageResource(R.mipmap.photo1);
                video_iv.setImageResource(R.mipmap.video2);
                camera_iv.setImageResource(R.mipmap.camera_btn3);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(cameraTag==1){
                            camera_iv.setImageResource(R.mipmap.camera_btn2);
                        }else if(cameraTag==0){
                            camera_iv.setImageResource(R.mipmap.camera_btn1);
                        }
                    }
                },200);
                handler.postDelayed(timeRunnable, 1000);
            }else{
                MyMethod.ShowDialog(PreviewActivity.this,R.string.device_save_full);
            }
            camera_iv.setEnabled(true);
        }

        @Override
        public void stopVideo() {
            videoStart = false;
            currentTime = 0;
            video_time.setText("");
            video_time.setVisibility(View.GONE);
            camera_iv.setImageResource(R.mipmap.camera_btn3);
            switch_btn.setEnabled(true);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(cameraTag==1){
                        camera_iv.setImageResource(R.mipmap.camera_btn2);
                    }else if(cameraTag==0){
                        camera_iv.setImageResource(R.mipmap.camera_btn1);
                    }

                }
            },200);
            camera_iv.setEnabled(true);
        }

        @Override
        public void takePhoto(File cacheFile) {
            if (isResume) {
                if (cacheFile != null && cacheFile.length() != 0) {
                    photoPath = cacheFile.getPath();
                    //Glide.with(PreviewActivity.this).load(cacheFile).into(pic_1);
                }
            }
        }

        @Override
        public void captureResponse() {
            final Bitmap bitmap = textureView.getBitmap();
            BitmapDrawable drawable = new BitmapDrawable(bitmap);
            int[] location = new int[2];
            int[] location2 = new int[2];
            params_fl_2.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            pic_1.getLocationOnScreen(location2);
            int x2 = location2[0];
            int y2 = location2[1];
            LogUtils.e(x+"--"+y);
            LogUtils.e(x2+"--"+y2);
            LogUtils.e(pic_1.getWidth()+"--"+pic_1.getHeight());
            // Log.e(TAG,textureView.getWidth()+"--"+textureView.getHeight());
            float fx = pic_1.getWidth()*1.0f/params_fl_2.getWidth();
            float fy = pic_1.getHeight()*1.0f/params_fl_2.getHeight();
            LogUtils.e(fx+"--"+fy);
            params_fl_2.setBackground(drawable);
            startAnimationSet(fx,fy,x2-x,y2-y,bitmap);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    bytes = baos.toByteArray();
                }
            }).start();
        }

        @Override
        public void battery(final int battery) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (battery > 80) {
                        battery_iv.setImageResource(BaseFinal.batteryIds[4]);
                    } else if (battery > 60) {
                        battery_iv.setImageResource(BaseFinal.batteryIds[3]);
                    } else if (battery > 40) {
                        battery_iv.setImageResource(BaseFinal.batteryIds[2]);
                    } else if (battery > 20) {
                        battery_iv.setImageResource(BaseFinal.batteryIds[1]);
                    } else {
                        battery_iv.setImageResource(BaseFinal.batteryIds[0]);
                    }
                }
            });
        }

        @Override
        public void SDSurplus(final int percent) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    space_iv.Percent(percent);
                    if(percent==0){
                        MyMethod.ShowDialog(PreviewActivity.this,R.string.device_save_null);
                    }
                }
            });
        }

    };

    boolean fragmentShow;
    CountDownTimer cdt = new CountDownTimer(5000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(!fragmentShow){
                this.cancel();
            }
        }

        @Override
        public void onFinish() {
            if(isResume){
                removeFragment();
                showAll();
            }
        }
    };

    private void showFragment(Fragment fragment) {
        fragmentShow = true;
        fragmentTransaction = fragmentManager.beginTransaction();
        if (showFlag == 3) {
            fragmentTransaction.replace(R.id.params_fl_2, fragment);
        } else {
            fragmentTransaction.replace(R.id.params_fl, fragment);
        }
        fragmentTransaction.commit();
        if(cdt!=null){
            cdt.cancel();
        }
        cdt.start();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogUtils.i("keyCode  =  "+keyCode);
        LogUtils.i("videoStart  =  "+videoStart);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(videoStart){
                new AlertDialog.Builder(PreviewActivity.this)
                        .setMessage(R.string.stop_video)
                        .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (showFlag == 3) {
                                    removeFragment();
                                } else {
                                    finish();
                                }
                            }
                        })
                        .setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                wifiService.stopVideo();
                                videoStart = false;
                            }
                        })
                        .create()
                        .show();
            }else{
                if (showFlag == 3) {
                    removeFragment();
                } else {
                    finish();
                }
            }

            return true;
        }
        return false;
    }

    private void removeFragment() {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (showFlag == 0) {
            fragmentTransaction.remove(wbFragment);
            wb_iv.setImageResource(R.mipmap.wb_1);
        } else if (showFlag == 1) {
            fragmentTransaction.remove(exposureFragment);
            exposure_iv.setImageResource(R.mipmap.exposure_1);
        } else if (showFlag == 2) {
            fragmentTransaction.remove(ratiosFragment);
            ratios_iv.setImageResource(R.mipmap.ratio_1);
        } else if (showFlag == 3) {
            fragmentTransaction.remove(bigImageFragment);
        } else if (showFlag == 4) {
            fragmentTransaction.remove(codeRateFragment);
            rate_iv.setImageResource(R.mipmap.qingxidu_1);
        }else if(showFlag == 5){
            fragmentTransaction.remove(cutDownFragment);
            Drawable drawableLeft = getResources().getDrawable(R.mipmap
                    .djs_1);
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
            djs_tv.setCompoundDrawables(drawableLeft, null, null, null);
        }
        fragmentTransaction.commit();
        showFlag = Integer.MAX_VALUE;
        fragmentShow = false;
    }

    byte[] bytes = null;

    @Override
    public void onClick(View v) {
        if (wifiService != null) {
            if(showFlag!=Integer.MAX_VALUE){
                removeFragment();
                return;
            }
            if (v == wb_iv) {
                wifiService.getWB();
            } else if (v == exposure_iv) {
                wifiService.getExposure();
            } else if (v == ratios_iv) {
                wifiService.getRatios();
            } else if (v == camera_iv) {
                final int time = cutDownMap.get(cutDownMode);
                if(time==0){
                    PZorSX();
                }else{
                    if(cameraTag==1&&videoStart){
                        PZorSX();
                        return;
                    }
                    CountDownTimer cdt_djs = new CountDownTimer(time*1000,1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            if(djs_tv!=null){
                                int xx = (int) (millisUntilFinished/1000);
                                String ss = xx+"s";
                                djs_tv.setText(ss);
                            }else{
                                this.cancel();
                            }
                        }

                        @Override
                        public void onFinish() {
                            if(isResume){
                                PZorSX();
                                String ss = time+"s";
                                djs_tv.setText(ss);
                                camera_iv.setEnabled(true);
                            }
                        }
                    };
                    cdt_djs.start();
                    camera_iv.setEnabled(false);
                }
            } else if (v == textureView) {
                removeFragment();
                showAll();
            } else if (v == rate_iv) {
                wifiService.getCodeRate();
            } else if(v == djs_tv){
                if (cutDownFragment == null) {
                    cutDownFragment = CutDownFragment.newInstance();
                }
                cutDownFragment.setmParam1(cutDownMode);
                showFragment(cutDownFragment);
                wb_iv.setImageResource(R.mipmap.wb_1);
                rate_iv.setImageResource(R.mipmap.qingxidu_1);
                exposure_iv.setImageResource(R.mipmap.exposure_1);
                ratios_iv.setImageResource(R.mipmap.ratio_1);
                Drawable drawableLeft = getResources().getDrawable(R.mipmap
                        .djs_2);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                djs_tv.setCompoundDrawables(drawableLeft, null, null, null);
                showFlag = 5;
            }
        }
        if (v == pic_1) {
            if (photoPath != null) {
                if (bigImageFragment == null) {
                    bigImageFragment = BigImageFragment.newInstance();
                }
                bigImageFragment.setmParam1(photoPath);
                showFlag = 3;
                showFragment(bigImageFragment);
                hideAll();
            } else if (bytes != null) {
                if (bigImageFragment == null) {
                    bigImageFragment = BigImageFragment.newInstance();
                }
                bigImageFragment.setBytes(bytes);
                showFlag = 3;
                showFragment(bigImageFragment);
            }
        }
    }

    //拍照或摄像指令
    private void PZorSX(){
        if (cameraTag == 1) {
            if (!videoStart) {
                wifiService.startVideo();
                camera_iv.setEnabled(false);
            } else {
                wifiService.stopVideo();
                camera_iv.setEnabled(false);
            }
        } else if (cameraTag == 0) {
            wifiService.takePicture();
        }
    }

    private void hideAll(){
       // right_rl.setVisibility(View.GONE);
        media_control.setVisibility(View.GONE);
        ratios_iv.setVisibility(View.GONE);
        exposure_iv.setVisibility(View.GONE);
        wb_iv.setVisibility(View.GONE);
        rate_iv.setVisibility(View.GONE);
        djs_tv.setVisibility(View.GONE);
    }

    private void showAll(){
       // right_rl.setVisibility(View.VISIBLE);
        media_control.setVisibility(View.VISIBLE);
        ratios_iv.setVisibility(View.VISIBLE);
        exposure_iv.setVisibility(View.VISIBLE);
        wb_iv.setVisibility(View.VISIBLE);
        rate_iv.setVisibility(View.VISIBLE);
        djs_tv.setVisibility(View.VISIBLE);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void close() {
        removeFragment();
    }

    @Override
    public void selectItem(int flag, int num) {
        LogUtils.e("flag = " + flag + "  num = " + num);
        cdt.cancel();
        cdt.start();
        if (wifiService != null) {
            if (flag == 0) {
                wifiService.setWB(num);
            } else if (flag == 1) {
                wifiService.setExposure(num);
            } else if (flag == 2) {
                wifiService.setRatios(num);
            } else if (flag == 4) {
                wifiService.setCodeRate(num);
            } else if(flag == 5){
                MyMethod.saveSingleValue(PreviewActivity.this,dcam,"cutDown",num);
                cutDownMode = num;
                if(cutDownFragment!=null){
                    cutDownFragment.setParamsSuccess(cutDownMode);
                }
                setDjs_Tv(cutDownMode);
            }
        }
    }

    private void setDjs_Tv(int num){
        if(num==0){
            djs_tv.setText("0s");
        }else if(num==1){
            djs_tv.setText("5s");
        }else if(num==2){
            djs_tv.setText("10s");
        }else if(num==3){
            djs_tv.setText("15s");
        }
    }

    private class WifiConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wifiService = ((WifiService.WifiBinder) service).getService();
            wifiService.setWifiServiceCallback3(wifiServiceCallback3);
            LogUtils.e("WifiConn = getPreviewData");
            wifiService.getRecordPolicy();
            wifiService.getOSD();
            wifiService.getTVMode();
            wifiService.getPreviewData();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        initView();
        cutDownMap.put(0,0);
        cutDownMap.put(1,5);
        cutDownMap.put(2,10);
        cutDownMap.put(3,15);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        LogUtils.e("onResume-------------------");
        if(!ServiceStatic.isWifiDeviceConnect){
            // TODO: 2018/5/23 测试关闭
            finish();
        }
        textureView.setSurfaceTextureListener(this);
        cutDownMode = MyMethod.getNum(this,dcam,"cutDown");
        setDjs_Tv(cutDownMode);
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e("onPause-------------------");
        isResume = false;
        releaseCodec();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e("PreviewActivity onDestroy");
        wifiService.setWifiServiceCallback3(null);
        unbindService(wifiConn);
        wifiConn = null;
    }

    private void CreateVideo() {
        isCreateView = true;
        try {
            videoCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
            MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, BaseStatic.SCREEN_HEIGHT, BaseStatic.SCREEN_WIDTH);
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
            videoCodec.configure(mediaFormat, mSurface, null, 0);
            videoCodec.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void decodeVideo(byte[] bytes, int length) {
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outputBufferIndex = videoCodec.dequeueOutputBuffer(bufferInfo, 0);
        while (outputBufferIndex >= 0) {
            if (bufferInfo.size > 0) {
                videoCodec.releaseOutputBuffer(outputBufferIndex, true);
            } else {
                videoCodec.releaseOutputBuffer(outputBufferIndex, false);
            }
            outputBufferIndex = videoCodec.dequeueOutputBuffer(bufferInfo, 0);
        }

        ByteBuffer[] inputBuffers = videoCodec.getInputBuffers();
        int inputBufferIndex = videoCodec.dequeueInputBuffer(0);
        if (inputBufferIndex >= 0) {
            ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
            inputBuffer.clear();
            inputBuffer.put(bytes, 0, length);
            videoCodec.queueInputBuffer(inputBufferIndex, 0, length, 0, 0);
        }
    }

    private void releaseCodec() {
        isCreateView = false;
        if (videoCodec != null) {
            videoCodec.release();
            videoCodec = null;
        }
    }

    private void initView() {
        fragmentManager = getSupportFragmentManager();
        wifiIntent = new Intent(this, WifiService.class);
        textureView = findViewById(R.id.textureView);
        wb_iv = findViewById(R.id.wb_iv);
        exposure_iv = findViewById(R.id.exposure_iv);
        ratios_iv = findViewById(R.id.ratios_iv);
        rate_iv = findViewById(R.id.rate_iv);
        battery_iv = findViewById(R.id.battery_iv);
        space_iv = findViewById(R.id.space_iv);
        camera_iv = findViewById(R.id.camera_iv);
        djs_tv = findViewById(R.id.djs_tv);
        //right_rl = findViewById(R.id.right_rl);
        media_control = findViewById(R.id.media_control);
        video_time = findViewById(R.id.video_time);
        switch_btn = findViewById(R.id.switch_btn);
        pic_1 = findViewById(R.id.pic_1);
        params_fl_2 = findViewById(R.id.params_fl_2);
        photo_iv = findViewById(R.id.photo_iv);
        video_iv = findViewById(R.id.video_iv);
        wb_iv.setOnClickListener(this);
        exposure_iv.setOnClickListener(this);
        ratios_iv.setOnClickListener(this);
        rate_iv.setOnClickListener(this);
        camera_iv.setOnClickListener(this);
        textureView.setOnClickListener(this);
        pic_1.setOnClickListener(this);
        djs_tv.setOnClickListener(this);
        switch_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cameraTag = 1;
                    camera_iv.setImageResource(R.mipmap.camera_btn2);
                    photo_iv.setImageResource(R.mipmap.photo1);
                    video_iv.setImageResource(R.mipmap.video2);
                } else {
                    cameraTag = 0;
                    camera_iv.setImageResource(R.mipmap.camera_btn1);
                    photo_iv.setImageResource(R.mipmap.photo2);
                    video_iv.setImageResource(R.mipmap.video1);
                }
            }
        });
    }

    public void startAnimationSet(float fx, float fy, int x, int y, final Bitmap bitmap) {
        //创建动画，参数表示他的子动画是否共用一个插值器
        AnimationSet animationSet = new AnimationSet(true);
        //添加动画
        TranslateAnimation translateAnimation = new TranslateAnimation(0,x,0,y);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f,fx,1.0f,fy);
        animationSet.addAnimation(scaleAnimation);
        animationSet.addAnimation(translateAnimation);
        //设置插值器
        animationSet.setInterpolator(new LinearInterpolator());
        //设置动画持续时长
        animationSet.setDuration(500);
        //设置动画结束之后是否保持动画的目标状态
        animationSet.setFillAfter(false);
        //设置动画结束之后是否保持动画开始时的状态
        animationSet.setFillBefore(true);
        //设置重复模式
        animationSet.setRepeatMode(AnimationSet.REVERSE);
        //设置重复次数
        animationSet.setRepeatCount(AnimationSet.INFINITE);
        //设置动画延时时间
        animationSet.setStartOffset(100);
        //取消动画
        //  animationSet.cancel();
        //释放资源
        // animationSet.reset();
        //开始动画
        params_fl_2.startAnimation(animationSet);
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                params_fl_2.setBackgroundResource(0);
                pic_1.setImageBitmap(bitmap);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        surfaceTexture = surface;
        mSurface = new Surface(surfaceTexture);
        if (isResume&&!isCreateView) {
            CreateVideo();
            if(wifiConn==null){
                wifiConn = new WifiConn();
                bindService(wifiIntent, wifiConn, BIND_AUTO_CREATE);
            }else{
                LogUtils.e("onSurfaceTextureAvailable = getPreviewData");
                wifiService.getPreviewData();
            }
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        LogUtils.e("StopPreview");
        if (wifiService != null) {
            wifiService.StopPreview();
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }
}
